<template>
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
        <el-form-item label="咨询师姓名">
            <el-input v-model="queryInfo.consultName" placeholder="请输入咨询师姓名" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-form-item>
    </el-form>
    <!-- 新增弹出框 -->
    <el-dialog v-model="showAddDialog" title="添加咨询信息">
        <el-form :model="newConsultInfo" :rules="addFormRules" ref="addFormRef" class="no-spacing-form">
            <el-form-item label="咨询师ID" prop="consultId">
                <el-input v-model="newConsultInfo.consultId" placeholder="请输入咨询师姓名" clearable />
            </el-form-item>
            <el-form-item label="咨询师姓名" prop="consultName">
                <el-input v-model="newConsultInfo.consultName" placeholder="请输入咨询师姓名" clearable />
            </el-form-item>
            <el-form-item label="咨询师头像" prop="consultImg">
                <el-upload
                    v-model:file-list="newConsultAvatarFileList"
                    class="avatar-uploader"
                    action="http://localhost:8080/file/upload"
                    :on-success="handleAvatarUploadSuccess('consultImg')"
                    :show-file-list="true"
                >
                    <el-image v-if="newConsultInfo.consultImg" :src="getImageUrl(newConsultInfo.consultImg)" class="avatar" :fit="fit" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="咨询师简介" prop="consultIntro">
                <el-input v-model="newConsultInfo.consultIntro" placeholder="请输入咨询师简介" clearable />
            </el-form-item>
            <el-form-item label="预约id" prop="appointmentId">
                <el-input v-model="newConsultInfo.appointmentId" placeholder="请输入预约id" clearable />
            </el-form-item>
            <el-form-item label="咨询用户名" prop="appointmentId">
                <el-input v-model="newConsultInfo.appointmentId" placeholder="请输入预约id" clearable />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="showAddDialog = false">取消</el-button>
            <el-button type="primary" @click="validateAndAdd">确定</el-button>
        </template>
    </el-dialog>
    <!-- 数据展示 -->
    <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="consultId" label="咨询 ID"></el-table-column>
        <el-table-column prop="consultName" label="咨询师姓名"></el-table-column>
        <el-table-column label="咨询师头像">
            <template #default="scope">
                <el-image :src="getImageUrl(scope.row.consultImg)" style="width: 50px; height: 50px" :fit="fit" />
            </template>
        </el-table-column>
        <el-table-column prop="consultIntro" label="咨询师简介"></el-table-column>
        <el-table-column prop="appointmentId" label="预约ID" v-if="false"></el-table-column>
        <el-table-column prop="userName" label="咨询用户名"></el-table-column>
        <el-table-column prop="createTime" label="预约时间"></el-table-column>
        <el-table-column prop="status" label="状态：0未完成，1已回复，未回复2"></el-table-column>
        <el-table-column fixed="right" label="操作" min-width="100">
            <template #default="scope">
                <el-button link type="primary" @click="onDel(scope.row.appointmentId)" size="small">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
         v-model="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1,5, 10, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
const handleSizeChange = (newSize) => {
    queryInfo.value.pageSize = newSize;
    // 更改每页数量时重置页码为 1
    queryInfo.value.pageNum = 1;
    getList();
};

const handleCurrentChange = (newPage) => {
    queryInfo.value.pageNum = newPage;
    getList();
};

const onSubmit = () => {
    // 搜索时重置页码为 1
    queryInfo.value.pageNum = 1;
    getList();
};

const tableData = ref([]);
const queryInfo = ref({
    pageNum: 1,
    pageSize: 5,
    consultId: null,
    consultName: '',
    consultImg: '',
    consultIntro: '',
    levelName: '',
    certName: '',
    certImage: '',
    userName:'',
    createTime:null,
    content:'',
    reply:'',
    reply_time:null,
    status:null
});
const total = ref(0);
const showAddDialog = ref(false);
const newConsultInfo = ref({
    consultId: '',
    consultName: '',
    consultImg: '',
    consultIntro: '',
    levelName: '',
    certName: '',
    certImage: '',
    userName:'',
    createTime:null,
    content:'',
    reply:'',
    reply_time:null,
    status:null
});
const newConsultAvatarFileList = ref([]);
const newConsultCertFileList = ref([]);
const showEditDialog = ref(false);
const editConsultInfo = ref({});
const editConsultAvatarFileList = ref([]);
const editConsultCertFileList = ref([]);
const showDeleteDialog = ref(false);
const deleteId = ref('');
const consultLevels = ref([]);
const certificateNames = ref([]);
const fit = ref('cover');

// 新增表单验证规则
const addFormRules = reactive({
    consultName: [
        { message: '请输入咨询师姓名', trigger: 'blur' }
    ],
    consultImg: [
        { message: '请上传头像', trigger: 'change' }
    ],
    consultIntro: [
        { message: '请输入咨询师简介', trigger: 'blur' }
    ],
    levelName: [
        { message: '请选择咨询等级', trigger: 'change' }
    ],
    certName: [
        { message: '请选择证书名称', trigger: 'change' }
    ],
    certImage: [
        { message: '请上传证书图片', trigger: 'change' }
    ]
});
// 新增默认空对象用于重置表单
const defaultNewConsultInfo = {
    consultId: '',
    consultName: '',
    consultImg: '',
    consultIntro: '',
    levelName: '',
    certName: '',
    certImage: '',
    userName:'',
    createTime:null,
    content:'',
    reply:'',
    reply_time:null,
    status:null
};




const getList = () => {
    axios.get('/consultInfoVo/getConsultInfo', {
        params: queryInfo.value
    }).then((resp) => {
        let result = resp.data;
        if (result.code === 1) {
            total.value = result.data.total;
            tableData.value = result.data.list;
        }
    }).catch((error) => {
        console.error('请求失败', error);
        if (error.response) {
            if (error.response.status === 404) {
                console.log('请求的资源未找到');
            } else if (error.response.status === 500) {
                console.log('服务器内部错误');
            }
        } else if (error.request) {
            console.log('请求发送失败，没有收到响应');
        } else {
            console.log('请求发生错误', error.message);
        }
    });
};

const getConsultLevels = () => {
    axios.get('/consult-level/selectName').then((response) => {
        if (response.data.code === 1) {
            consultLevels.value = response.data.data;
        }
    }).catch((error) => {
        console.error('获取咨询等级失败', error);
    });
};

const getCertificateNames = () => {
    axios.get('/consultCertificate/selectCertificate').then((response) => {
        if (response.data.code === 1) {
            certificateNames.value = response.data.data;
        }
    }).catch((error) => {
        console.error('获取证书名称失败', error);
    });
};

const handleAvatarUploadSuccess = (field, type = 'add') => {
    return (response, uploadFile) => {
        if (response.code === 1) {
            if (type === 'add') {
                if (field === 'consultImg') {
                    newConsultInfo.value.consultImg = response.data;
                } else if (field === 'certImage') {
                    newConsultInfo.value.certImage = response.data;
                }
            } else if (type === 'edit') {
                if (field === 'consultImg') {
                    editConsultInfo.value.consultImg = response.data;
                } else if (field === 'certImage') {
                    editConsultInfo.value.certImage = response.data;
                }
            }
        } else {
            ElMessage.error('图片上传失败');
        }
    };
};
// 增加
const validateAndAdd = async () => {
    try {
        const data = {
            consult: {
                name: newConsultInfo.value.consultName,
                img: newConsultInfo.value.consultImg,
                intro: newConsultInfo.value.consultIntro,
                sex: '',
                levelId: 0,
                address: '',
                authentication: 0
            },
            consultLevel: {
                name: newConsultInfo.value.levelName
            },
            consultCertificate: {
                certName: newConsultInfo.value.certName,
                certImage: newConsultInfo.value.certImage
            }
        };

        const response = await axios.post('/consult/addAll', data);
        if (response.data.code === 1) {
            // 显示警告弹框
            await ElMessageBox.alert('三联查不允许该操作', '警告', {
                confirmButtonText: '确定'
            });
            // 重置表单和文件列表
            newConsultInfo.value = { ...defaultNewConsultInfo };
            newConsultAvatarFileList.value = [];
            newConsultCertFileList.value = [];
            showAddDialog.value = false;
            getList();
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，三联查不允许该操作');
    }
};


const onDel = (id) => {
    axios.delete(`/consultInfoVo/${id}`).then((resp) => {
        let result = resp.data;
        if (result.code === 1) {
            ElMessage.success('删除成功');
            getList();
        } else {
            ElMessage.error('删除失败');
        } 
    })
};
const scope = ref({});
const getImageUrl = (fileName) => {
    return `http://localhost:8080/file/downLoad?fileName=${fileName}`;
};

onMounted(() => {
    getList();
    getConsultLevels();
    getCertificateNames();
});
</script>

<style scoped>
.no-spacing-form .el-form-item {
    margin-bottom: 0;
}

.no-spacing-form .el-form-item__content {
    padding: 0;
}
</style>